<template>
  <div>

    <div class="btn-group" style="margin:20px;margin-bottom:11px;float: right;">
      <el-row>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          @click="handleAdd"
        >添加</el-button>
      </el-row>
    </div>

    <div style="margin:20px;">
      <el-table
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="100"
        />
        <el-table-column
          prop="title"
          label="标题"
        />
        <el-table-column
          prop="src"
          label="图片"
          width="150"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.src">
              <img class="imgBg" :src="getImgUrl(scope.row)" alt="">
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="sort"
          label="排序"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="150"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editClick(scope.row)">编辑</el-button>
            <el-button type="text" style="color:red;" @click="deleteClick(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top:20px;text-align: right;">
        <el-pagination
          background
          :page-size="limit"
          :pager-count="7"
          layout="total, prev, pager, next"
          :total="tableCount"
          @current-change="handleCurrentChange"
        />
      </div>

    </div>

    <div>

      <el-dialog :title="from_title" :visible.sync="dialogVisible" :before-close="handleClose">
        <el-form ref="ruleForm" :model="dataForm" label-width="120px" label-position="left">
          <el-form-item label="分类名称" prop="title">
            <el-input v-model="dataForm.title" />
          </el-form-item>
          <el-form-item label="logo" prop="image">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              action="#"
              name="file"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="src" :src="src" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>

          <el-form-item label="排序" prop="sort">
            <el-input v-model="dataForm.sort" />
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="info" @click="handleClose">关 闭</el-button>
          <el-button type="primary" @click="handleDialogOk">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>

</template>

<script>
export default {
  data() {
    return {
      src: '',
      from_title: '',
      dataForm: {},
      tableData: [],
      dialogVisible: false,
      page: 1,
      limit: 10,
      tableCount: 0
    }
  },
  mounted() {
    this.handleCurrentList()
  },
  methods: {
    getImgUrl(row) {
      return row.src
    },
    handleCurrentList() {
      this.$request.post('/store/get_store_cate', { page: this.page, limit: this.limit }).then(res => {
        if (res.code == 2000) {
          this.tableData = res.data.item
          this.tableCount = res.data.count
        }
      })
    },
    handleCurrentChange(val) {
      this.page = val
      this.handleCurrentList()
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }

      const formdata = new FormData()
      const ali = new FormData()
      formdata.append('file', file)
      const config = {
        onUploadProgress: progressEvent => {
          if (progressEvent.lengthComputable) {
            this.progress = true
            this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100)
              .toFixed(2))
          }
        }
      }

      this.$request.post('/Upload/upload', formdata, config).then(res => {
        if (res.code == 2000) {
          this.src = res.url
          this.dataForm.src = res.url
        }
      })

      return isJPG && isLt2M
    },
    deleteClick(row) {
      console.log(row)
      this.$confirm('是否删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'waring'
      }).then(() => {
        this.$request.post('/store/del_store_cate', { id: row.id }).then(res => {
          if (res.code == 2000) {
            this.$message({ type: 'success', message: '删除成功!' })
            this.page = 1
            this.handleCurrentList()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    // 打开新增
    handleAdd() {
      this.dialogVisible = true
      this.dataForm = {}
      this.from_title = '新建'
      this.src = ''
    },
    // 打开编辑
    editClick(val) {
      this.from_title = '编辑'
      this.dialogVisible = true
      this.dataForm = { 'title': val.title, 'src': val.src, 'id': val.id, 'sort': val.sort }
      this.src = val.src
      console.log(this.dataForm)
    },
    // 提交结果
    handleDialogOk() {
      this.$refs['ruleForm'].validate(async(valid) => {
        console.log(valid)
        if (valid) {
          console.log(this.dataForm)
          if (this.dataForm.id) {
            this.$request.post('/store/edit_store_cate', this.dataForm).then(res => {
              if (res.code == 2000) {
                this.$message({ type: 'success', message: res.msg })
                this.dialogVisible = false
                this.handleCurrentList()
              }
            })
          } else {
            this.$request.post('/store/add_store_cate', this.dataForm).then(res => {
              if (res.code == 2000) {
                this.$message({ type: 'success', message: res.msg })
                this.dialogVisible = false
                this.handleCurrentList()
              }
            })
          }
        }
      })
    },
    handleClose() {
      this.$refs['ruleForm'].resetFields()
      this.dialogVisible = false
    }
  }
}
</script>

<style>
  .avatar{
    width:100px;
    height: 100px;
  }
  .imgBg{
    width:40px;
    height:40px;
  }
</style>
